const {chromium, firefox} = require('playwright');

module.exports = {
  schedule: {
    cron: '0 50 8 * * ?',
    type: 'worker',
    env: ['pachong'],
  },

  async task(ctx) {
    let root_url = 'https://xyzrank.com/#/new-podcasts';
    // let root_url = 'https://xyzrank.com/#/hot-podcasts';
    let browser = await chromium.launch({headless: true});

    try {
      const page = await browser.newPage();
      await page.setExtraHTTPHeaders({'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.70 Safari/537.36'});
      await page.goto(root_url, {waitUntil: 'domcontentloaded'});
      await page.waitForTimeout(2000);
      await page.waitForSelector('tr.gridjs-tr.rank-tr');

      let eles = await page.$$('tr.gridjs-tr.rank-tr');

      for (let i = 1; i < eles.length; i++) {
        const el = eles[i];
        const loginname = await el.$eval('.podcast-name', v => v.innerText);
        const tag = await el.$eval('.genre-link', v => v.innerText);
        const url = await el.$eval('.podcast-name', v => v.href);
        let rss;
        if (await el.$('.icon-link-rss')) {
          rss = await el.$eval('.icon-link-rss', v => v.href);
        }

        const user = await ctx.model.User.findOne({loginname});
        if (!user) {
          ctx.logger.info('podcast新增作者:', loginname);
          await ctx.service.crawlerSvc.createPodcastUser(loginname, tag, url, rss);
          let topics = await ctx.service.commonSvc.commonPodcastXyzNew(loginname);
          const result = await ctx.service.topicSvc.importTopics(topics);
          ctx.logger.info(loginname, '第一次导入的播客数量:', result);
        }
        ctx.logger.info(i, eles.length);
      }
    } catch (e) {
    } finally {
      await browser.close();
    }

  },
};
